package com.example.chamberlainserver.config;

import com.example.chamberlainserver.Entry.MaterialCategory;
import com.example.chamberlainserver.Service.MaterialCategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import java.util.Arrays;
import java.util.List;

/**
 * 数据初始化配置类
 * 用于在应用启动时初始化基础数据
 */
@Configuration
public class DataInitializer {

    private static final Logger logger = LoggerFactory.getLogger(DataInitializer.class);

    @Autowired
    private MaterialCategoryService materialCategoryService;

    /**
     * 初始化物资分类数据
     */
    @Bean
    @Order(1)
    public CommandLineRunner initMaterialCategories() {
        return args -> {
            logger.info("开始初始化物资分类数据...");
            
            // 检查是否已存在分类数据
            List<MaterialCategory> existingCategories = materialCategoryService.getAllCategories();
            if (!existingCategories.isEmpty()) {
                logger.info("物资分类数据已存在，跳过初始化。现有分类数量: {}", existingCategories.size());
                return;
            }
            
            // 定义顶级分类
            List<String> topCategories = Arrays.asList("文娱", "卫生", "维修工具", "日常用品", "防疫", "118物资");
            
            // 初始化顶级分类
            for (int i = 0; i < topCategories.size(); i++) {
                String categoryName = topCategories.get(i);
                MaterialCategory category = new MaterialCategory();
                category.setName(categoryName);
                category.setParentId(null); // 顶级分类
                category.setDescription(categoryName + "相关物资");
                category.setSortOrder(i + 1); // 排序序号从1开始
                
                try {
                    materialCategoryService.addCategory(category);
                    logger.info("创建顶级分类成功: {}", categoryName);
                } catch (Exception e) {
                    logger.error("创建顶级分类失败: {}, 原因: {}", categoryName, e.getMessage());
                }
            }
            
            // 为每个顶级分类添加子分类示例
            addSubCategories("文娱", Arrays.asList("书籍", "体育用品", "棋牌", "乐器"));
            addSubCategories("卫生", Arrays.asList("清洁工具", "清洁剂", "个人卫生用品", "垃圾处理"));
            addSubCategories("维修工具", Arrays.asList("电工工具", "木工工具", "管道工具", "五金配件"));
            addSubCategories("日常用品", Arrays.asList("厨房用品", "生活用品", "办公用品", "床上用品"));
            addSubCategories("防疫", Arrays.asList("口罩", "消毒用品", "防护服", "测温设备"));
            addSubCategories("118物资", Arrays.asList("应急药品", "应急工具", "应急食品", "应急照明"));
            
            logger.info("物资分类数据初始化完成");
        };
    }
    
    /**
     * 为指定的父分类添加子分类
     * @param parentName 父分类名称
     * @param subCategoryNames 子分类名称列表
     */
    private void addSubCategories(String parentName, List<String> subCategoryNames) {
        // 获取父分类
        MaterialCategory parentCategory = materialCategoryService.getCategoryByName(parentName);
        if (parentCategory == null) {
            logger.error("添加子分类失败: 父分类 '{}' 不存在", parentName);
            return;
        }
        
        // 添加子分类
        for (int i = 0; i < subCategoryNames.size(); i++) {
            String subCategoryName = subCategoryNames.get(i);
            MaterialCategory subCategory = new MaterialCategory();
            subCategory.setName(subCategoryName);
            subCategory.setParentId(parentCategory.getId());
            subCategory.setDescription(parentName + "-" + subCategoryName);
            subCategory.setSortOrder(i + 1);
            
            try {
                materialCategoryService.addCategory(subCategory);
                logger.info("创建子分类成功: {} -> {}", parentName, subCategoryName);
            } catch (Exception e) {
                logger.error("创建子分类失败: {} -> {}, 原因: {}", parentName, subCategoryName, e.getMessage());
            }
        }
    }
}